using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace Gj
{
    public class ScrollHelper : NodeHelper, IPointerDownHandler, IPointerUpHandler, IPointerEnterHandler, IPointerExitHandler
    {
        public bool vertical;
        public bool horizontal;
        public ScrollRect scrollRect;
        public NodeHelper[] list;
        public bool invert;
        private bool _allow;
        private bool drag;
        private bool enter;

        protected override BindDataType bindDataType => BindDataType.Bool;

        private void Update()
        {
            // if (drag)
            // {
            //     Debug.LogErrorFormat("OnPointerDarg: {0}", SystemInput.center);
            // }
            if (drag) Emit(UIEvent.Drag);
        }


        public void OnPointerDown(PointerEventData eventData)
        {
            // Debug.LogErrorFormat("OnPointerDown: {0}", eventData.position);
            var obj = eventData.pointerCurrentRaycast.gameObject;
            if (obj != null)
            {
                var helper = obj.GetComponent<NodeHelper>();
                if (helper != null && helper.index > -1)
                {
                    Emit(helper.index, UIEvent.Down);
                    drag = true;
                    enter = true;
                }
            }
        }

        public void OnPointerUp(PointerEventData eventData)
        {
            // Debug.LogErrorFormat("OnPointerUp: {0}", eventData.position);
            if (!drag) return;
            Emit(UIEvent.Up);
            drag = false;
            enter = false;
        }

        public void OnPointerEnter(PointerEventData eventData)
        {
            // Debug.LogErrorFormat("OnPointerEnter: {0}", eventData.position);
            // Emit(UIEvent.Enter);
        }

        public void OnPointerExit(PointerEventData eventData)
        {
            // Debug.LogErrorFormat("OnPointerExit: {0}", eventData.position);
            if (!enter) return;
            Emit(UIEvent.Exit);
            enter = false;
        }

        protected override void BindData(bool b)
        {
            _allow = invert ? !b : b;
            scrollRect.horizontal = _allow ? horizontal : false;
            scrollRect.vertical = _allow ? vertical : false;
            for (var i = 0; i < list.Length; i++) list[i].SetData(_allow);
        }
    }
}